<?php

class User extends KF_Auth_Controller
{
    private $_data = array();

    function index()
    {
        if (IS_POST)
        {
            $where = array();
            $group_id = isset($_POST['group_id']) ? intval($_POST['group_id']) : 0;
            $status = isset($_POST['status']) ? intval($_POST['status']) : 0;
            if ($group_id > 0) $where[] = "id in(select uid from kfsy_sjxt.kf_auth_group_access where group_id=$group_id)";
            if ($status > 0) $where[] = "status=$status";

            $config = array(
                'table' => 'kfsy_sjxt.kf_auth_users',
                'columns' => array(
                    array('db' => 'mobile'),
                    array('db' => 'nickname'),
                    array('db' => 'groups'),
                    array('db' => 'create_time'),
                    array('db' => 'login_time'),
                    array('db' => 'login_ip'),
                    array('db' => 'status'),
                    array('db' => 'id')
                ),
                'where' => implode(' and ', $where)
            );
            $this->load->library('dataTables', $config);
            $result = $this->datatables->search();

            if ($result['data'])
            {
                $user_ids = array();
                foreach ($result['data'] as $i => $data)
                {
                    $user_ids[$i] = $data['id'];
                }
                $sql = 'select uid,title from kfsy_sjxt.kf_auth_group_access a join kfsy_sjxt.kf_auth_group g on a.group_id=g.id where uid in(' . implode(',', $user_ids) . ')';
                $res_groups = DB::select_db($this->user_id, $sql, 1);
                foreach ($res_groups as $group)
                {
                    $groups[$group['uid']][] = $group['title'];
                }
                foreach ($user_ids as $i => $uid)
                {
                    $result['data'][$i]['groups'] = isset($groups[$uid]) ? implode('，', $groups[$uid]) : '';
                }
            }

            exit(json_encode($result));
        }

        $sql = "SELECT id,title FROM kfsy_sjxt.kf_auth_group WHERE status=1";
        $this->_data['groups'] = DB::select_db($this->user_id, $sql, 1);

        $this->_data['auth'] = $this->check2('user', 'add', 'edit', 'del');

        $this->load->view('user/index', $this->_data);
    }

    function add()
    {
        $id = $uid = isset($_GET['id']) ? intval($_GET['id']) : 0;

        if (IS_POST)
        {
            $mobile = isset($_POST['mobile']) ? Util::make_str_replace(trim($_POST['mobile'])) : '';
            $password = Util::make_str_replace(trim($_POST['password']));
            $nickname = Util::make_str_replace(trim($_POST['nickname']));
            $groups = isset($_POST['group']) ? $_POST['group'] : array();

            if ($id <= 0)
            {
                if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) $this->error('手机号格式不正确');
                if (empty($password)) $this->error('密码不能为空');
            }
            if (empty($nickname)) $this->error('昵称不能为空');

            if ($id <= 0)
            {
                $sql = "select count(*) as t from kfsy_sjxt.kf_auth_users where mobile='$mobile'";
                $count = DB::count_db($this->user_id, $sql);
                if ($count > 0) $this->error('手机号已存在');
            }

            mysql_query("BEGIN");   //开始执行Innodb事务
            //新增或编辑用户
            if ($id > 0)
            {
                $sql = "update kfsy_sjxt.kf_auth_users set nickname='$nickname',modify_time=now()";
                if (!empty($password)) $sql .= ",password='" . md5($password) . "'";
                $sql .= " where id=$id";
                $result = DB::update_db($this->user_id, $sql) > 0;
            }
            else
            {
                $password = md5($password);
                $sql = "insert into kfsy_sjxt.kf_auth_users(mobile,password,nickname,create_time,status) values('$mobile','$password','$nickname',now(),1)";
                $uid = DB::insert_db($this->user_id, $sql);
                $result = $uid > 0;
            }

            //删除用户权限
            if ($result && $id > 0)
            {
                $sql = "delete from kfsy_sjxt.kf_auth_group_access where uid=$id";
                $result = DB::delete_db($this->user_id, $sql) > 0;
            }

            //新增用户权限
            if ($result && $groups)
            {
                foreach ($groups as $group)
                {
                    $values[] = "('$uid','$group')";
                }
                $values = implode(',', $values);
                $sql = "INSERT INTO kfsy_sjxt.kf_auth_group_access(uid,group_id) VALUES $values";
                $result = DB::insert_db($this->user_id, $sql) > 0;
            }

            if ($result)
            {
                mysql_query("COMMIT");  //执行以上插入或更新
            }
            else
            {
                mysql_query("ROLLBACK");    //失败回滚操作
            }
            mysql_query("END"); //执行完成

            $result ? $this->success('保存用户信息成功') : $this->error('保存用户信息失败');
        }

        if ($id > 0)
        {
            $sql = "select * from kfsy_sjxt.kf_auth_users where id=$id";
            $this->_data['user'] = DB::select_db($this->user_id, $sql, 0);

            $sql = "select group_id from kfsy_sjxt.kf_auth_group_access where uid=$id";
            $res_access = DB::select_db($this->user_id, $sql, 1);
            foreach ($res_access as $res)
            {
                $this->_data['access'][$res['group_id']] = 1;
            }
        }

        $sql = "SELECT id,title FROM kfsy_sjxt.kf_auth_group WHERE status=1";
        $this->_data['groups'] = DB::select_db($this->user_id, $sql, 1);

        $this->load->view('user/add', $this->_data);
    }

    function edit()
    {
        $this->add();
    }

    function del()
    {
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        if ($id <= 0) $this->error('用户编号错误');

        $sql = "update kfsy_sjxt.kf_auth_users set status=(case status when 3 then 1 else 3 end) where id=$id";
        $result = DB::update_db($this->user_id, $sql) > 0;
        $result ? $this->success('修改用户状态成功') : $this->error('修改用户状态失败');
    }
}